<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="时间范围:" prop="dateRange">
        <el-date-picker
          v-model="dataForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="success" plain @click="_exportCSV()">导出</el-button>
        <el-button type="info" @click="clientReportVisible = true">配置导出字段</el-button>
        <el-button @click="printContent">打印</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      id="clientReportTable"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="index"
        width="50"
        header-align="center"
        align="center"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="clientName"
        header-align="center"
        align="center"
        label="客户名称">
      </el-table-column>
      <el-table-column
        prop="remainAmount"
        header-align="center"
        align="center"
        label="欠款金额">
      </el-table-column>
      <el-table-column
        prop="orderNum"
        header-align="center"
        align="center"
        label="订单数量">
      </el-table-column>
    </el-table>
    <el-dialog
      title="提示"
      :visible.sync="clientReportVisible"
      width="30%"
    >
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
    <el-button @click="clientReportVisible = false">取 消</el-button>
    <el-button type="primary" @click=handleTitle>确 定</el-button>
  </span>
    </el-dialog>
  </div>

</template>

<script>
  // import AddOrUpdate from './clientreportvo-add-or-update'
  const cityOptions = ['客户名称', '欠款金额', '订单数量']
  const alertTypeIntGetStringMap = {
    '客户名称': 'clientName',
    '欠款金额': 'remainAmount',
    '订单数量': 'orderNum'
  }
  export default {
    data () {
      return {
        dataForm: {
          key: '',
          dateRange: ''
        },
        clientReportVisible: false,
        titleList: '客户名称,欠款金额,订单数量',
        keyList: 'clientName,remainAmount,orderNum',
        beginDate: '',
        endDate: '',
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        checkAll: true,
        checkedCities: ['客户名称', '欠款金额', '订单数量'],
        cities: cityOptions,
        isIndeterminate: true
      }
    },
    // components: {
    //   AddOrUpdate
    // },
    activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/funds/clientreportvo/listAll'),
          method: 'post',
          params: this.$http.adornParams({
            // 'page': this.pageIndex,
            // 'limit': this.pageSize,
            // 'key': this.dataForm.key,
            'beginDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[0],
            'endDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[1]
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      _exportCSV () {
        this.$http({
          url: this.$http.adornUrl('/funds/clientreportvo/exportCSV'),
          method: 'post',
          responseType: 'blob',
          params: this.$http.adornParams({
            'titles': this.titleList,
            'keys': this.keyList,
            'beginDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[0],
            'endDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[1]
          })
        }).then((response) => {
          if (response) {
            let url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/ms-txt.numberformat:@'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '客户未收款表汇总.csv')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          } else {
            this.$message.error('请设置要导出的字段')
          }
        })
      },

      // 导出
      _export () {
        this.$http({
          url: this.$http.adornUrl('/funds/clientreportvo/export'),
          method: 'post',
          responseType: 'blob',
          params: this.$http.adornParams({
            'beginDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[0],
            'endDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[1]
          })
        }).then((response) => {
          let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'})
          if (window.navigator.msSaveOrOpenBlob) {
            // 如果需要改名字，前台可以自动生成
            navigator.msSaveBlob(blob, '客户未收款表汇总')
          } else {
            let link = document.createElement('a')
            let evt = document.createEvent('HTMLEvents')
            evt.initEvent('click', false, false)
            link.href = URL.createObjectURL(blob)
            link.download = '客户未收款表汇总'
            link.style.display = 'none'
            document.body.appendChild(link)
            link.click()
            window.URL.revokeObjectURL(link.href)
          }
        }).catch((e) => {
          console.log(e)
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/funds/clientreportvo/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },

      handleCheckAllChange (val) {
        this.checkedCities = val ? cityOptions : []
        this.isIndeterminate = false
      },
      handleCheckedCitiesChange (value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.cities.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
      },
      handleTitle () {
        this.titleList = ''
        this.keyList = ''

        for (let i = 0, leng = this.checkedCities.length; i < leng; i++) {
          let title = this.checkedCities[i]

          let key = alertTypeIntGetStringMap[title]

          if (i !== leng - 1) {
            this.titleList += title + ','

            this.keyList += key + ','
          } else {
            this.titleList += title

            this.keyList += key
          }
        }

        this.clientReportVisible = false
      },
      // 打印页面内容
      printContent () {
        console.log(11)
        let wpt = document.querySelector('#clientReportTable')
        let newContent = wpt.innerHTML
        let oldContent = document.body.innerHTML

        document.body.innerHTML = newContent
        window.print() // 打印方法
        // window.localtion.reload();
        history.go(0)
        document.body.innerHTML = oldContent
      }

    }
  }
</script>
